package com.loooooo.pm2024.modules.res.controller;


import com.loooooo.pm2024.data.Result;
import com.loooooo.pm2024.modules.res.model.ResourceFile;
import com.loooooo.pm2024.modules.res.selector.FileInfoSelector;
import com.loooooo.pm2024.modules.res.service.ResourceFileService;
import com.loooooo.pm2024.service.IdService;
import com.loooooo.pm2024.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/resource/file")
public class ResourceFileController {

    @Autowired
    ResourceFileService resourceFileService;

    @GetMapping(value = "/list")
    String list() {
        return "res/resource.file.list";
    }

    @PostMapping(value = "/list", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    Result list(@RequestBody(required = false) FileInfoSelector selector) {

        if (selector == null) selector = new FileInfoSelector();


        if (selector.getPageSize() != null) {
            if (selector.getPageNo() == null || selector.getPageNo() < 1) {
                selector.setPageNo(1);
            }
            Result result = new Result();
            int count = resourceFileService.count(selector);
            result.set("total", count);
            if (count > (selector.getPageSize() * (selector.getPageNo() - 1))) {
                result.setData(resourceFileService.list(selector));
            }
            return result.set("now", System.currentTimeMillis());
        }
        return Result.success(resourceFileService.list(selector)).set("now", System.currentTimeMillis());
    }

    @PutMapping(value = "/upload/**", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result fileUpload(
            @ModelAttribute ResourceFile resourceFile,
            HttpServletRequest request, @RequestBody byte[] data) {
        //String key = request.getRequestURI().substring("/upload/".length());

        return Result.success(null).set("affect", 0);
    }

    @Autowired
    IdService idService;

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    public Result fileUpload2(
            @RequestParam(value = "rename", required = false) Integer rename,
            @ModelAttribute ResourceFile resourceFile,
            StandardMultipartHttpServletRequest request) {
        System.out.println("upload1 ...");
        Map<String, MultipartFile> mm = request.getFileMap();
        MultipartFile multipartFile = null;
        for (Map.Entry<String, MultipartFile> entry : mm.entrySet()) {
            multipartFile = entry.getValue();
            System.out.println("upload12 ...");
        }
        String key = request.getRequestURI().substring("/upload/".length());

        System.out.println("upload3 ...");
        String contentType = multipartFile.getContentType();
        System.out.println(String.format("Content-Type:%s", contentType));
        if (Objects.equals(1, rename)) {
            String oldname = multipartFile.getOriginalFilename();
            String extname = oldname.substring(oldname.lastIndexOf("."));
            resourceFile.setFilename(String.format("%s%s", idService.nextId(), extname));
        }
        int r = resourceFileService.update(resourceFile, multipartFile);
        return Result.success(resourceFile).set("success", 1).set("affect", r).set("url", "/resource/file/download?id=" + resourceFile.getId());
    }

    @RequestMapping(value = "/download")
    @ResponseBody
    void download(
            @RequestParam(value = "id") Long id,
            HttpServletRequest request, HttpServletResponse response) {
        ResourceFile rf = resourceFileService.get(id);
        File dir = new File("/image2/pm2024/res/", rf.getPath());
        File file = new File(dir.getAbsolutePath(), rf.getFilename());


        response.setContentType(request.getServletContext().getMimeType(file.getName()));
        CacheControl cacheControl = CacheControl.maxAge(10, TimeUnit.DAYS);
        response.setHeader(HttpHeaders.CACHE_CONTROL, cacheControl.getHeaderValue());
        try {
            IOUtils.write(file, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
